﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Castle.Windsor;
using Mammoth.Factories;
using Mammoth.Repositories;
using Mammoth.Services;
using MySql.Data.MySqlClient;

namespace Mammoth
{
    /// <summary>
    /// Interaction logic for SplashScreen.xaml
    /// </summary>
    public partial class SplashScreen : Window
    {
        public SplashScreen()
        {
            InitializeComponent();
        }

        protected override void OnContentRendered(EventArgs e)
        {
            base.OnContentRendered(e);
            Task.Factory.StartNew(Initialize);
        }

        private void Initialize()
        {
            var inf = new InstallerFactory();

            var c = new WindsorContainer();
            c.Install(inf.GetInstaller());

            try
            {
                var cnf = c.Resolve<IDatabaseConfiguration>();
                c.Resolve<IDataSessionFactory>().Configure(cnf);

                Dispatcher.Invoke(() =>
                {
                    var mw = c.Resolve<MainWindow>();
                    mw.Show();
                    Close();
                });
            }
            catch (MySqlException)
            {
                MessageBox.Show("Gagal melakukan konesi ke MySQL. Server MySQL offline atau informasi database di file konfigurasi salah", "Galat");
                ThreadSafeClose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                ThreadSafeClose();
            }
        }

        private void ThreadSafeClose()
        {
            Dispatcher.Invoke(() =>
            {
                Close();
            });
        }
    }
}
